#include "common.h"

namespace SkyID
{

bool CheckExt(const char *fileName, const char *ext)
{
	const char* fnExt = strrchr(fileName, '.');
	return fnExt ? strcasecmp(++fnExt, ext) == 0 : false;

	// TODO: this one should be case insensitive (e.g. PNg == png == PNG == pNg)
	// strcasecmp isn't portable (came from BSD, doesn't exist in C standard)
}

namespace Log
{

bool create()
{
	// create log file
	FILE *logFile = fopen(LOG_FILE_NAME, "w");
	if (!logFile)
		return false;

	fclose(logFile);
	return true;
}

int write(LogFlags flags, const char *format, ...)
{
	int result = 0;

	va_list ap;
	// try to open file
	FILE *logFile = fopen(LOG_FILE_NAME, "a+");
	if (NULL == logFile)
		return result;

	// write timestamp at beginning of the line
	if (flags & LOG_TS)
	{
		tm *t;
		time_t tt;
		time(&tt);
		t = localtime(&tt);
		mktime(t);
		result += fprintf(logFile, "[%02d:%02d:%02d] ",
			t->tm_hour, t->tm_min, t->tm_sec);
	}

	// write parsed line to the file
	va_start(ap, format);
	result += vfprintf(logFile, format, ap);
	va_end(ap);

	// write newline character at the end of the line
	if (flags & LOG_NL)
	{
		fputc('\n', logFile);
		result++;
	}

	fclose(logFile);
	return result;
}

} // namespace Log

} // namespace SkyID
